<template>
  <el-dialog :visible.sync="currentVisible"
             append-to-body
             destroy-on-close
             @open="open"
             :close-on-click-modal="false"
             title="Clone Form"
             custom-class="clone-widget-dialog"
             width="470px">
    <el-form :model="form" ref="form" :rules="dataRule" v-loading="loading">
      <p>
        You can directly use all the configuration of the widget, or you can
        reset the settings
      </p>

      <el-form-item prop="formTitle" label="Name">
        <el-input v-model="form.formTitle"
                  :maxlength="100"
                  :placeholder="$t('custom.dataset.name')"></el-input>
      </el-form-item>
      <el-form-item prop="roleIds"
                    :label="$t('user.role')">
        <el-select v-model="form.roleIds"
                   filterable
                   clearable
                   multiple
                   collapse-tags
                   default-first-option
                   style="width: 100%"
                   :placeholder="$t('custom.tenant.assignRole.selectRole')">
          <el-option v-for="(item, index) in roleList"
                     :key="index"
                     :value="item.roleId"
                     :label="item.name"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="description"
                    :label="$t('custom.reports.description')">
        <el-input v-model="form.description"
                  type="textarea"
                  :maxlength="500"
                  :rows="3"
                  :placeholder="$t('custom.reports.description')"></el-input>
      </el-form-item>
      <fm-generate-form :data="formInfo.formSchema" v-if="!formLoading" v-show="false" ref="generateForm"></fm-generate-form>
    </el-form>
    <template slot="footer">
      <el-button size="small"
                 @click="currentVisible = false">Cancel</el-button>
      <el-button type="primary"
                 size="small"
                 @click="onSave">Confirm</el-button>
    </template>
  </el-dialog>
</template>

<script>
import {isIncludeSymbol} from "@/utils/validate";

export default {
  name: 'clone-form',
  props: {
    visible:{
      type: Boolean,
      default: false
    },
    cloneFormCode: {
      type: String,
    }
  },
  data () {
    return {
      form: {
        formTitle: '',
        roleIds: '',
        description: ''
      },
      roleList: [],
      loading: false,
      formInfo: {},
      formLoading: false,
    }
  },
  computed: {
    currentVisible: {
      get () {
        return this.visible
      },
      set (val) {
        this.$emit('update:visible', val)
      }
    },
    dataRule () {
      var validateSymbol = (rule, value, callback) => {
        if (!isIncludeSymbol(value)) {
          return callback(new Error(this.$t('validate.isIncludeSymbol')))
        }
        callback()
      }
      return {
        formTitle: [
          { required: true, message: 'Please enter the name', trigger: 'blur', pattern: '[^ \x22]+' },
          { validator: validateSymbol, trigger: 'blur' },
          { validator: this.validateName, trigger: 'blur' }
        ],
        roleIds: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        description: [
          { required: true, message: 'Please enter the description', trigger: 'blur', pattern: '[^ \x22]+' }
        ]
      }
    }
  },
  methods: {
    async open () {
      this.loading = true
      await this.getFormInfo()
      await this.getRoles()
      this.loading = false
    },
    async getFormInfo () {
      this.formLoading = true
      const { getFormDataInfo } = this.$interface.reports
      const { data : { data } } = await getFormDataInfo({ formCode: this.cloneFormCode })
      this.formInfo = data
      this.form = {
        formTitle: `${data.formTitle}Clone`,
        roleIds: data.roleIds,
        description: data.description
      }
      this.formLoading = false
    },
    async validateName (rule, value, callback) {
      try {
        let params = {
          formTitle: this.form.formTitle,
        }
        const { getCheckFromNameApi } = this.$interface.reports
        const { data: response } = await getCheckFromNameApi(params)
        if (response.code !== 0) {
          throw new Error('The name is already exists')
        }
        callback()
      } catch (error) {
        callback(error)
      }
    },
    async getRoles () {
      const { getClientRoleListApi } = this.$interface.system
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      const { data: response } = await getClientRoleListApi(params)
      if (response.code !== 0) {
        throw response.msg
      }
      this.roleList = response.data || []
    },
    async onSave () {
      try {
        this.loading = true
        await this.$refs['form'].validate()
        const params = {
          businessType: 'Custom',
          status: 'Published',
          tenantCode: this.$store.state.user.tenantCode,
          integration: [],
          ...this.form,
          formSchema: this.formInfo.formSchema,
          dataContent: this.formInfo.dataContent
        }
        this.$refs.generateForm.getData(false).then(async res=>{
          params.dataContent = res
          const { addOrUpdateFormApi } = this.$interface.reports
          const { data: { data } } = await addOrUpdateFormApi(params)
          this.$message.success(data.msg)
          this.currentVisible = false
          this.$emit('success')
        })
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    }
  }
}
</script>
<style lang="scss">
.clone-widget-dialog.el-dialog {
  background-image: url("#{$--ossLink}/app/other/add_report_bg.png");
  background-position: center;
  background-repeat: no-repeat;
  background-size: 100% 100%;

  p {
    margin-top: 0;
  }
}
</style>
